package ocmd

import (
	"fmt"
	"osiris/errors"
	"osiris/logger"
	"osiris/ocrypto/ed25519"
	"osiris/p2p"
	"sync"
)

// PeersHandler peers命令handler
type PeersHandler struct{}

// Handle 查看peers相关信息
// peers: 显示PeerStore中所有节点的peer.ID
// peers addr:显示每个节点的所有Multiaddr
// peers pubkey: 显示每个节点的pubkey（ed25519+Base64）
//
//	@receiver handler
//	@param inputs
//	@param wg
//	@return error
func (handler *PeersHandler) Handle(inputs []string, wg *sync.WaitGroup) error {
	defer wg.Done()

	switch len(inputs) {
	//peers: 显示所有PeerID
	case 1:
		showAllPeerID()
		return nil

	case 2:
		{
			switch inputs[1] {
			//peers addr：显示每个节点的所有Multiaddr
			case ADDR:
				showAllPeerMultiaddr()
				return nil

			//peers pubkey: 显示每个节点的pubkey（ed25519+Base64）
			case PUBKEY:
				showAllPeerPubKey()
				return nil

			default:
				return &errors.CommandInputError{
					Msg: "unknown command",
				}
			}
		}

	default:
		return &errors.CommandInputError{
			Msg: "unknown command",
		}
	}

}

func showAllPeerID() {
	peerIDs := p2p.GetPeerIDs()
	logger.Println("Here are the peers stored in Ha.PeerStore:")
	for _, peerID := range peerIDs {
		logger.Printf("  %s\n", peerID.String())
	}
}
func showAllPeerMultiaddr() {
	peerIDs := p2p.GetPeerIDs()
	logger.Println("Here are the multiaddrs for each peerID stored in Ha.PeerStore:")
	for _, peerID := range peerIDs {
		logger.Printf("  %s\n", peerID.String())
		addrs := p2p.GetAddrs(peerID)
		for _, addr := range addrs {
			logger.Printf("      %s\n", addr.String())
		}
	}
}

func showAllPeerPubKey() {
	peerIDs := p2p.GetPeerIDs()
	logger.Println("Here are the multiaddrs for each peerID stored in Ha.PeerStore:")
	for _, peerID := range peerIDs {
		pubKey := p2p.GetPubKey(peerID)
		pubKeyStr, err := ed25519.PubKeyToStr(pubKey)
		if err != nil {
			continue
		}
		logger.Printf(" peerID: %s,  pubkey: %s\n", peerID.String(), pubKeyStr)
	}
}

func (handler *PeersHandler) PrintHelp() {
	printCommand(fmt.Sprintf("%s %s", PEERS, ADDR), "show all the multiaddrs for each peerID stored in Ha.PeerStore")
	printCommand(fmt.Sprintf("%s %s", PEERS, PUBKEY), "show all the pubkey(ECC+BASE64) for each peerID stored in Ha.PeerStore")
}
